package com.cman777.springc.elasticsearch.config;

import com.cman777.springc.elasticsearch.properties.ESConfigProperties;
import org.apache.http.HttpHost;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


/**
 * @author chenzhicong
 * @time 2020/6/10 12:21
 */
@Configuration
@EnableConfigurationProperties(ESConfigProperties.class)
public class ESClientConfig {
    @Autowired
    private ESConfigProperties esConfigProperties;


    @Bean
    @ConditionalOnProperty("es")
    public RestHighLevelClient client() {
        HttpHost[] httpHosts = esConfigProperties.getHosts().stream().map(h->new HttpHost(h.getHost(),h.getPort(),h.getSchema()))
                .toArray(HttpHost[]::new);
        RestClientBuilder builder = RestClient.builder(httpHosts);
        // 异步httpclient连接延时配置
        builder.setRequestConfigCallback(new RestClientBuilder.RequestConfigCallback() {
            @Override
            public RequestConfig.Builder customizeRequestConfig(RequestConfig.Builder requestConfigBuilder) {
                requestConfigBuilder.setConnectTimeout(esConfigProperties.getConnectTimeOut());
                requestConfigBuilder.setSocketTimeout(esConfigProperties.getSocketTimeOut());
                requestConfigBuilder.setConnectionRequestTimeout(esConfigProperties.getConnectionRequestTimeOut());
                return requestConfigBuilder;
            }
        });
        // 异步httpclient连接数配置
        builder.setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
            @Override
            public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
                httpClientBuilder.setMaxConnTotal(esConfigProperties.getMaxConnectNum());
                httpClientBuilder.setMaxConnPerRoute(esConfigProperties.getMaxConnectPerRoute());
                return httpClientBuilder;
            }
        });
        RestHighLevelClient client = new RestHighLevelClient(builder);
        return client;
    }



}
